package tdd.xuchun.test.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import cn.hutool.core.util.StrUtil;
import tdd.xuchun.test.model.Host;
import tdd.xuchun.test.util.BizException;
import tdd.xuchun.test.util.HttpUtil;
import tdd.xuchun.test.util.SSH2Util;
import tdd.xuchun.test.util.TarUntil;

@Service("easyNmonService")
public class EasyNmonServiceImpl implements tdd.xuchun.test.service.IEasyNmonService {

	@SuppressWarnings("finally")
	@Override
	// 上传并启动easyNmon
	public boolean upAndRun(Host host, int cover) {
		SSH2Util ssh2Util = null;
		String localpath = new EasyNmonServiceImpl().getClass().getClassLoader().getResource("/").getPath();
		boolean flag = false;
		try {
			ssh2Util = new SSH2Util(host.getAddr(), host.getUsername(), host.getPassword(), host.getPort());
			String path = ssh2Util.runCommand("pwd").replaceAll("info:", "").replaceAll("\n", "");
			String file = ssh2Util.runCommand("ls|grep runeasynmon.sh");
			ssh2Util.runCommand("pkill -9 easyNmon");
			if (cover == 1 || file.indexOf("runeasynmon.sh") < 0) {
				ssh2Util.runCommand("rm easyNmon.tar.gz");
				ssh2Util.putFile(localpath + "nmon", "easyNmon.tar.gz", path);
				for (int i = 0; i < 3; i++) {
					Thread.sleep(1000);
					String sb = ssh2Util.runCommand("ls");
					if (sb.contains("easyNmon.tar.gz")) {
						break;
					}
				}
				ssh2Util.runCommand("tar -xvf easyNmon.tar.gz");
				ssh2Util.putFile(localpath + "nmon", "nmonanaly.xlsm", path + "/easyNmon/report/");
			}
			ssh2Util.runCommand("echo \"cd easyNmon\" > runeasynmon.sh");
			String commtent = "";
			if (StrUtil.isNotEmpty(host.getOstype())) {
				commtent = "echo \"nohup ./easyNmon -p " + host.getEznmonport() + " -np ./nmon/nmon_"
						+ host.getOstype().replaceAll("\\s*", "") + " >/dev/null 2>&1&\" >> runeasynmon.sh";

			} else {
				commtent = "echo \"nohup ./easyNmon -p " + host.getEznmonport()
						+ " >/dev/null 2>&1&\" >> runeasynmon.sh";
			}
			ssh2Util.runCommand(commtent);
			ssh2Util.runCommand("sh " + path + "/runeasynmon.sh");
			flag = true;
		} catch (Exception e) {
			flag = false;
			throw e;
		} finally {
			if (ssh2Util != null) {
				try {
					ssh2Util.close();
				} catch (Exception e) {
					throw new BizException(e);
				}
			}
			return flag;
		}

	}

//执行指令并检查状态码
	@Override
	public int accessTheURL(Host host, String urlSuffix) {
		String url = "http://" + host.getAddr() + ":" + host.getEznmonport() + "/" + urlSuffix;
		return HttpUtil.getStateCode(url);
	}

	@SuppressWarnings("finally")
	@Override
	public boolean clearReport(Host host) {
		SSH2Util ssh2Util = null;
		boolean flag = true;
		try {
			ssh2Util = new SSH2Util(host.getAddr(), host.getUsername(), host.getPassword(), host.getPort());
			String path = ssh2Util.runCommand("pwd").replaceAll("info:", "").replaceAll("\n", "");
			ssh2Util.runCommand("rm " + path + "/easyNmon/report/" + host.getName() + "_report.zip");
			String rmcom = "find " + path + "/easyNmon/report " + " -name \"" + host.getName()
					+ "*\" -type  d |xargs rm -rf ";
			ssh2Util.runCommand(rmcom);
		} catch (Exception e) {
			flag = false;
			throw new BizException(e);
		} finally {
			if (ssh2Util != null) {
				try {
					ssh2Util.close();
				} catch (Exception e) {
					throw new BizException(e);
				}
			}
			return flag;
		}

	}

	/**
	 * 文件夹打包并下载
	 */

	@SuppressWarnings("finally")
	@Override
	public boolean getReportPackage(Host host) {
		SSH2Util ssh2Util = null;
		boolean flag = true;
		try {
			ssh2Util = new SSH2Util(host.getAddr(), host.getUsername(), host.getPassword(), host.getPort());
			String path = ssh2Util.runCommand("pwd").replaceAll("info:", "").replaceAll("\n", "");
			ssh2Util.runCommand("rm " + path + "/easyNmon/report/" + host.getName() + "_report.zip");
			ssh2Util.runCommand(
					"zip " + path + "/easyNmon/report/" + host.getName() + "_report.zip easyNmon/report/* -r ");
		} catch (Exception e) {
			flag = false;
			throw new BizException(e);
		} finally {
			if (ssh2Util != null) {
				try {
					ssh2Util.close();
				} catch (Exception e) {
					throw new BizException(e);
				}
			}
			return flag;
		}
	}

	// 查询easyNmon包中的nmon文件支持的操作系统
	@SuppressWarnings("finally")
	@Override
	public List<String> getEzNmonOS() {
		String file = new EasyNmonServiceImpl().getClass().getClassLoader().getResource("/").getPath()
				+ "/nmon/easyNmon.tar.gz";
		List<String> fileArray = new ArrayList<String>();
		try {
			List<String> fileNames = TarUntil.visitTARGZ(new File(file));
			for (int i = 0; i < fileNames.size(); i++) {
				String filetype = (String) fileNames.get(i);
				if (filetype.contains("/nmon/nmon_")) {
					int begin = filetype.indexOf("nmon_") + 5;
					fileArray.add(StrUtil.sub(filetype, begin, filetype.length()));
				}
			}

		} catch (IOException e) {
			throw new BizException(e);
		} finally {
			return fileArray;
		}
	}

}
